import React, { useState, useEffect } from 'react';
import { connect } from 'dva';
import { Row, Col, Form, Input, Select, Modal, message, Spin } from 'antd';
import request from '@/utils/request';
import SelectBusiObj from './common/SelectBusiObj';
import BusiElementInfo from './addTab/BusiElementInfo';

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 8 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 },
  },
};

const namespace = 'busiComponent';

function BusiCompnentAdd(props) {
  const { getFieldDecorator } = props.form;
  const [selectBusiObjVisibleFlag, setSelectBusiobjVisibleFlag] = useState(false); // 选择业务对象弹窗展示/隐藏标记
  const [objTypeList, setObjTypeList] = useState([]); // 组件类型
  const [spinning, setSpinning] = useState(false);

  useEffect(() => {
    initData();
  }, [props.busiComponentAddType]);

  useEffect(() => {
    initData();
  }, [props.selectBusiComponent]);

  const initData = () => {
    getObjTypeList();
    if (props.busiComponentAddType === 'add') {
      props.form.setFieldsValue({
        objType: '1000',
      });
    } else if (props.busiComponentAddType === 'modify') {
      setSpinning(true);
      request('pmc/pms/busiObj/queryById', {
        method: 'GET',
        data: { busiObjId: props.selectBusiComponent.objId },
      }).then(res => {
        if (res && res.success === true) {
          props.form.setFieldsValue({
            objId: res.data.busiObjId,
            busiObjName: res.data.busiObjName,
            busiCompId: props.selectBusiComponent.busiCompId,
            busiCompName: props.selectBusiComponent.busiCompName,
            busiCompCode: props.selectBusiComponent.busiCompCode,
            objType: '1000',
          });
          setSpinning(false);
        }
      });
    }
  };

  const getObjTypeList = () => {
    const tempObjTypeList = [
      {
        name: '标准组件',
        value: '1000',
      },
      {
        name: '个性化组件',
        value: '1100',
      },
    ];
    setObjTypeList(tempObjTypeList);
  };

  // dva 保存新增对象组件时选中的业务对象
  const saveSelectBusiObjAdd = params => {
    const { dispatch } = props;
    dispatch({
      type: `${namespace}/saveSelectBusiObjAdd`,
      payload: params,
    });
  };

  // dva 保存新增对象组件弹窗显示/隐藏标记
  const saveBusiComponentAddVisibleFlag = params => {
    const { dispatch } = props;
    dispatch({
      type: `${namespace}/saveBusiComponentAddVisibleFlag`,
      payload: params,
    });
  };

  // dva 保存新增对象组件类型
  const saveBusiComponentAddType = params => {
    const { dispatch } = props;
    dispatch({
      type: `${namespace}/saveBusiComponentAddType`,
      payload: params,
    });
  };

  // dva 保存选中对象组件
  const saveSelectBusiComponent = params => {
    const { dispatch } = props;
    dispatch({
      type: `${namespace}/saveSelectBusiComponent`,
      payload: params,
    });
  };

  // dva 保存对象组件元素列表
  const saveBusiElementAddList = params => {
    const { dispatch } = props;
    dispatch({
      type: `${namespace}/saveBusiElementAddList`,
      payload: params,
    });
  };

  // 选择业务对象
  const handleSelectBusiObj = () => {
    setSelectBusiobjVisibleFlag(true);
  };

  // 选择业务对象回调函数
  const selectBusiObjCallBacks = {
    selectBusiObjCallBack: data => {
      props.form.setFieldsValue({
        busiObjName: data.busiObjName,
        objId: data.busiObjId,
        busiCompName: data.busiObjName,
        busiCompCode: data.busiObjNbr,
      });
      saveSelectBusiObjAdd(data);
    },
    handleVisibleFlag: flag => {
      setSelectBusiobjVisibleFlag(flag);
    },
  };

  const clearPropStates = () => {
    saveBusiElementAddList([]);
    saveBusiComponentAddType('');
    saveSelectBusiObjAdd({});
    saveSelectBusiComponent({});
  };

  // 新增/修改对象组件
  const handleOk = () => {
    props.form.validateFields((err, formData) => {
      if (err) return;

      setSpinning(true);
      formData.elementList = props.busiElementAddList;

      if (props.busiComponentAddType === 'add') {
        request('pmc/pcms/busiComponent/add', { data: formData }).then(res => {
          if (res && res.success === true) {
            setSpinning(false);
            message.success('新增成功');
            saveBusiComponentAddVisibleFlag(false);
            clearPropStates();
          } else {
            setSpinning(false);
            if (res && res.errMessage) {
              message.error(res.errMessage);
            } else {
              message.error('新增失败');
            }
          }
        });
      } else if (props.busiComponentAddType === 'modify') {
        request('pmc/pcms/busiComponent/update', { data: formData }).then(res => {
          if (res && res.success === true) {
            setSpinning(false);
            message.success('修改成功');
            saveBusiComponentAddVisibleFlag(false);
            clearPropStates();
          } else {
            setSpinning(false);
            if (res && res.errMessage) {
              message.error(res.errMessage);
            } else {
              message.error('修改失败');
            }
          }
        });
      }
    });
  };

  const handleCancel = () => {
    saveBusiComponentAddVisibleFlag(false);
    clearPropStates();
  };

  const handleCompCodeChange = e => {
    const inputVal = e.currentTarget.value;
    props.busiElementAddList.map(item => {
      if (item.elementCode !== null && item.elementCode !== undefined) {
        const vArr = item.elementCode.split('_');
        if (vArr !== null && vArr.length >= 2) {
          item.elementCode = `${inputVal}_${vArr.slice(1).join('_')}`;
        }
      }
      return null;
    });
    const tempAddlist = [...props.busiElementAddList];
    saveBusiElementAddList(tempAddlist);
  };

  return (
    <Modal
      title={props.busiComponentAddType === 'add' ? '新增对象组件' : '修改对象组件'}
      visible={props.modalVisible}
      width="80%"
      height="70%"
      destroyOnClose
      onCancel={() => {
        handleCancel();
      }}
      onOk={() => {
        handleOk();
      }}
    >
      <Spin spinning={spinning}>
        <Form>
          <Row>
            <Col span={12}>
              <Form.Item label="对象组件名称" {...formItemLayout}>
                {getFieldDecorator('busiCompName', {
                  rules: [
                    {
                      required: true,
                      message: '对象组件名称不能为空',
                    },
                  ],
                })(
                  <Input
                    placeholder="请输入对象组件名称"
                    disabled={
                      !(
                        props.busiComponentAddType === 'add' ||
                        props.busiComponentAddType === 'modify'
                      )
                    }
                    maxLength={20}
                  />
                )}
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="对象组件编码" {...formItemLayout}>
                {getFieldDecorator('busiCompCode', {
                  rules: [
                    {
                      required: true,
                      message: '对象组件编码不能为空',
                    },
                  ],
                })(
                  <Input
                    placeholder="请输入对象组件编码"
                    disabled={
                      !(
                        props.busiComponentAddType === 'add' ||
                        props.busiComponentAddType === 'modify'
                      )
                    }
                    maxLength={30}
                    onBlur={e => handleCompCodeChange(e)}
                  />
                )}
              </Form.Item>
            </Col>
          </Row>
          <Row>
            <Col span={12}>
              <Form.Item label="业务对象" {...formItemLayout}>
                {getFieldDecorator('busiObjName', {
                  rules: [
                    {
                      required: true,
                      message: '业务对象不能为空',
                    },
                  ],
                })(
                  <Input.Search
                    disabled={props.busiComponentAddType !== 'add'}
                    readOnly
                    placeholder="请选择业务对象"
                    onSearch={handleSelectBusiObj}
                    allowClear
                  />
                )}
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="对象类型" {...formItemLayout}>
                {getFieldDecorator('objType')(
                  <Select style={{ width: '100%' }} showSearch disabled allowClear>
                    {objTypeList.length
                      ? objTypeList.map(item => {
                          return (
                            <Select.Option value={item.value} key={item.value}>
                              {item.name}
                            </Select.Option>
                          );
                        })
                      : null}
                  </Select>
                )}
              </Form.Item>
            </Col>
          </Row>
          <Row style={{ display: 'none' }}>
            <Col span={1}>
              <Form.Item label="业务对象Id" {...formItemLayout}>
                {getFieldDecorator('objId')(<Input disabled />)}
              </Form.Item>
            </Col>
          </Row>
          <Row style={{ display: 'none' }}>
            <Col span={1}>
              <Form.Item label="对象组件Id" {...formItemLayout}>
                {getFieldDecorator('busiCompId')(<Input disabled />)}
              </Form.Item>
            </Col>
          </Row>
        </Form>
        {/* 选择业务对象 */}
        {selectBusiObjVisibleFlag ? (
          <SelectBusiObj modalVisible={selectBusiObjVisibleFlag} {...selectBusiObjCallBacks} />
        ) : null}
        <BusiElementInfo />
      </Spin>
    </Modal>
  );
}

export default connect(({ busiComponent }) => ({
  selectBusiComponent: busiComponent.selectBusiComponent,
  busiComponentAddType: busiComponent.busiComponentAddType,
  selectBusiComponentAddFlag: busiComponent.selectBusiComponentAddFlag,
  busiElementAddList: busiComponent.busiElementAddList,
}))(Form.create()(BusiCompnentAdd));
